﻿using System;
using System.Text.RegularExpressions;

namespace Microsoft.AspNetCore.Http
{
    /// <summary>
    /// Reqeust 扩展操作类
    /// </summary>
    public static class RequestExtensions
    {
        private static readonly Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);

        /// <summary>
        /// 判断是否为移动设备
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsMobileDevice(this HttpRequest request)
        {
            var userAgent = request.UserAgent();
            return b.IsMatch(userAgent);
        }

        /// <summary>
        /// 判断是否为 IPad
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsIPad(this HttpRequest request)
        {
            var userAgent = request.UserAgent();
            return userAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) > 0;
        }

        /// <summary>
        /// 获得请求 UserAgent 字符串 读取 Header["User-Agent"]
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string UserAgent(this HttpRequest request)
        {
            return request.Headers["User-Agent"];
        }

        /// <summary>
        /// 获得请求绝对路径
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string AbsoluteUrl(this HttpRequest request)
        {
            return $"{request.Scheme}://{request.Host}{request.PathBase}{request.Path}{request.QueryString}";
        }
    }
}
